<?php
namespace app\api\model;

use think\Exception;
use think\Model;

use think\Cache;

class TaskModel extends Model
{
	protected $table = 'ly_task';

	/**
		拆分碎片
	**/
	public function publishTask(){
		$token			= request()->param('token','','trim') ;
        $lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型

		//判断nft有效性

        $data['uid']=0;
		if($token){
			$userArr = explode(',',auth_code($token,'DECODE'));

			$data['uid'] = $userArr[0];
		}
		$nft_id= request()->param('nft_id',0,'intval') ;
		$nftInfo=db('nft')->where(['id'=>$nft_id])->find();
		if(empty($nftInfo)){
			return json(['code'=>0,'code_dec'=>config($lang.'.lang2')[2]]);
		}
		if($nftInfo['uid'] != $data['uid']){
			return json(['code'=>0,'code_dec'=>config($lang.'.task')[0]]);
		}
		if($nftInfo['status'] !=1 || $nftInfo['state']!=1 ||$nftInfo['is_move']!=0 ){
			return json(['code'=>0,'code_dec'=>config($lang.'.task')[1]]);
		}
		if(!in_array($nftInfo['from'],[1,2])){
			return json(['code'=>0,'code_dec'=>config($lang.'.task')[2]]);
		}
		$data['nft_id']=$nft_id;
        $data['total_number'] = request()->param('total_number',0,'intval') ;
		$data['surplus_number'] = request()->param('total_number',0,'intval') ;

		$data['person_time'] = request()->param('person_time',0,'intval') ;
		$data['credit_type'] = request()->param('credit_type',0,'intval') ;
		$data['reward_price'] = request()->param('reward_price',0,'intval') ;
		$data['release_price'] = request()->param('release_price',0,'intval') ;
		$data['compound_num'] =  request()->param('total_number',0,'intval') ;
		$data['recovery_price'] = request()->param('recovery_price',0,'intval') ;
		//$data['end_time'] = strtotime(request()->param('end_time',date('Y-m-d H:i:s'),'intval')) ;
		$data['start_time'] = request()->param('start_time',0,'intval') ;
		$data['uids'] = request()->param('uids','','trim') ;
		if($data['credit_type']==0){
			$data['credit_type']=$nftInfo['credit_type'];
		}
		$data['status']=$data['start_time']==0?2:1;


        //数据验证

		// $validate = validate('app\api\validate\Nft');
		// if(!$validate->scene('add')->check($data)){
		// 	//抛出异常
		// 	return json(['code'=>0,'code_dec'=>$validate->getError()]);
		// }


        $data['order_number'] ='B'.date('YmdHis').rand(0,9).rand(0,9).rand(0,9).rand(0,9) ;
		$data['trade_number'] ='L'.date('YmdHis').rand(0,9).rand(0,9).rand(0,9).rand(0,9) ;
        $data['add_time'] =time();

		$res = $this->insert($data);
		//碎片状态修改
		model('Nft')->where(['id'=>$nft_id])->update([
			'state'=>2,
			'reward_price'=>$data['reward_price'],
			'recovery_price'=>$data['recovery_price'],
			'release_price'=>$data['release_price'],
			'total_number'=>$data['total_number'],
			'compound_num'=>$data['compound_num']
		]);

        //给自己添加nft碎片
		db('users_goods')->insert([
             'uid'=>$data['uid'],
			 'nft_id'=>$nft_id,
			 'total_number'=>$data['total_number'],
			 'status'=>1,
			 'reward_price'=>$data['reward_price'],
			 'recovery_price'=>$data['recovery_price'],
			 'release_price'=>$data['release_price'],
			 'compound_num'=>$data['compound_num'],
			 'create_time'=>time(),
		]);


		return json(['code'=>1,'data'=>[],'code_dec'=>config($lang.'.lang2')[3]]);

	}

	/**
		获取任务列表
	**/
	public function getTaskList(){

		$param		= input('post.');
        $lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
        $token			= (input('post.token')) ? input('post.token') : '';
        if(!$token){
            //return json(['code'=>0,'code_dec'=>'用户信息不存在']);
        }
		$where = 'a.nft_id !=0 ';
		$uid=0;
		if($token){
			$userArr	= explode(',',auth_code($token,'DECODE'));
			$uid		= $userArr[0];
			//$where.=" and a.uid=$uid";

		}
		$fields="a.*,n.name,n.file,a.credit_type,u.username,u.nickname,u.header";
		$obj	= $this->alias('a')->field($fields);

		if(isset($param['uid']) && !empty($param['uid'])){
			$where.=" and a.uid = {$param['uid']}";
		}
        if(isset($param['nft_id']) && !empty($param['nft_id'])){
            $where.=" and a.nft_id = {$param['nft_id']}";
        }
        if(isset($param['task_type']) && !empty($param['task_type'])){
            $where.=" and a.task_type = {$param['task_type']}";
        }
		if(isset($param['status']) && !empty($param['status'])){
			$where.=" and a.status = {$param['status']}";
		}
        if(isset($param['notendtime']) && !empty($param['notendtime'])){
            $where.=" and a.end_time>0 and a.end_time>".time();
        }
		if(isset($param['keywords']) && !empty($param['keywords'])){
			$where.=" and (n.name like '%{$param['keywords']}%' or u.nickname like '%{$param['keywords']}%' )";
		}
		if(isset($param['is_collect']) && !empty($param['is_collect'])){
			$obj	= $obj->join('users_task_collect c','a.id=c.task_id','left');
			$where.=" and c.uid = {$uid}";
		}
		//每页记录数
		$pageSize	= (isset($param['pagesize']) and $param['pagesize']) ? $param['pagesize'] : 10;
		//当前页
		$page		= (isset($param['page']) and $param['page']) ? $param['page'] : 1;
        $data	= $obj->join('nft n','a.nft_id=n.id','left')
			->join('users u','a.uid=u.id','left')
            ->where($where)
            ->order('a.add_time desc')
            ->paginate($pageSize)
            ->toArray();

		$usersCollect=db('users_task_collect')->where(['uid'=>$uid])->column('task_id');
        $statusArr= config($lang.'.taskstatus');
		foreach ($data['data'] as $key => &$value) {
			$value['file']=$value['file']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$value['file']):'';
            $value['header']=$value['header']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$value['header']):'';
            $value['add_time']=date('Y-m-d H:i:s',$value['add_time']);
            $statusStr = $value['status'];
            if (count($statusArr)>$statusStr){
                $statusStr = $statusArr[$value['status']];
            }
            $value['statusStr']= $statusStr;
            $value['credit_type_str']= getCreditTypeName($value['credit_type']);

			$value['is_collect']=in_array($value['id'],$usersCollect)?1:0;
		}
		return $data;
	}


	//获取任务信息
	public function getTaskinfo(){

        $param			= input('post.');

        $token			= (input('post.token')) ? input('post.token') : '';
        $lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型

		$where = 'a.nft_id !=0';
        if (isset($param['id'])){
            $where .= ' and a.id= '.$param['id'];
        }
        if (isset($param['status'])){
            $where .= ' and a.status= '.$param['status'];
        }

		$uid=0;
		if($token){
			$userArr	= explode(',',auth_code($token,'DECODE'));
			$uid		= $userArr[0];
			//$where.=" and a.uid=$uid";

		}


		$fields="a.id,a.status,a.nft_id,a.release_price,a.recovery_price,a.reward_price,a.person_time,a.total_number,a.receive_number,a.compound_num,a.add_time,a.end_time,n.name,n.file,a.credit_type,n.characteristic,n.content,u.username,u.nickname,u.header";
        $data	= $this->alias('a')
            ->field($fields)
			->join('nft n','a.nft_id=n.id','left')
			->join('users u','a.uid=u.id','left')
            ->where($where)
            ->find();

		$usersCollect=db('users_task_collect')->where(['uid'=>$uid])->column('task_id');
		$data['file']=$data['file']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$data['file']):'';
		$data['header']=$data['header']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$data['header']):'';
		$data['add_time']=date('Y-m-d H:i:s',$data['add_time']);
        $data['available_number']= $data['total_number']- $data['receive_number'];
        $statusArr= config($lang.'.taskstatus');
        $statusStr = $data['status'];
        if (count($statusArr)>$statusStr&&isset($statusArr[$data['status']])){
            $statusStr = $statusArr[$data['status']];
        }
		$data['statusStr']= $statusStr;
		$data['credit_type_str']= getCreditTypeName($data['credit_type']);

        $data['is_collect']=in_array($data['id'],$usersCollect)?1:0;

		return $data;
	}
	//获取任务信息
	public function collectTask(){
		$param			= input('post.');
		$task_id=isset($param['task_id'])?$param['task_id']:0;
		$token			= (input('post.token')) ? input('post.token') : '';
        $lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型

		$uid=0;
		if($token){
			$userArr	= explode(',',auth_code($token,'DECODE'));
			$uid		= $userArr[0];
		}
		$info=db('users_task_collect')->where(['uid'=>$uid,'task_id'=>$task_id])->find();
		if($info){
			db('users_task_collect')->where(['id'=>$info['id']])->delete();
			return json(['code'=>1,'code_dec'=>config($lang.'.lang2')[3]]);
		}else{
			db('users_task_collect')->insert(['uid'=>$uid,'task_id'=>$task_id,'create_time'=>time()]);
			return json(['code'=>1,'code_dec'=>config($lang.'.lang2')[3]]);
		}
	}


	//撤销任务
	public function revokeTask(){

		$param			= input('post.');
		$userArr		= explode(',',auth_code($param['token'],'DECODE'));
		$uid			= $userArr[0];
		$username		= $userArr[1];
		$id				= (input('post.id')) ? input('post.id') : 0;	// 任务ID;

		$lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型

		if(!$id){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		$info = $this->where(array(['id','=',$id],['uid','=',$uid]))->find();

		if(!$info){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}
		if(!in_array($info['status'],[1,2])){
			return ['code'=>0, 'code_dec'=>config($lang.'.task')[3]];
		}

		$is_up	=	$this->where(array(['id','=',$id]))->update(array('status'=>4));//撤销

		if(!$is_up){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}
		//把数量重新入到客户碎片表
		if($info['task_type']==1){
		    db('users_goods')->where(['nft_id'=>$info['nft_id'],'uid'=>$uid])->setInc('available_number', $info['surplus_number']);
		}
		// $userBalance_p		= 	model('UserTotal')->where('uid', $uid)->value('balance');	// 获取用户的余额

		// $total_price		=	$info['total_price']	+	$info['task_pump'];

		// $is_up_to = model('UserTotal')->where('uid', $uid)->setInc('balance', $total_price);
		// if(!$is_up_to){

		// 	$this->where(array(['id','=',$id],['uid','=',$uid],['status','=',5]))->update(array('status'=>1));//撤销
		// 	return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		// }

		// 流水

		// $financial_data_p['uid'] 					= $uid;
		// $financial_data_p['username'] 				= $username;
		// $financial_data_p['order_number'] 			= $info['order_number'];
		// $financial_data_p['trade_number'] 			= 'L'.trading_number();;
		// $financial_data_p['trade_type'] 			= 10;
		// $financial_data_p['trade_before_balance']	= $userBalance_p;
		// $financial_data_p['trade_amount'] 			= $total_price;
		// $financial_data_p['account_balance'] 		= $userBalance_p + $total_price;
		// $financial_data_p['remarks'] 				= config($lang.'.lang')[159];
		// $financial_data_p['types'] 					= 1;	// 用户1，商户2

		// model('common/TradeDetails')->tradeDetails($financial_data_p);

		return ['code'=>0, 'code_dec'=>config($lang.'.lang')[42]];
	}

    //版税买入卖出
    public function royTask(){

        $param			= input('post.');
        $token			= (input('post.token')) ? input('post.token') : '';
        $userArr    	= explode(',',auth_code($token,'DECODE'));
        $uid			= $userArr[0];
        $username		= $userArr[1];
        $lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
        $task_type		= (input('post.task_type')) ? input('post.task_type') : 1;	// 语言类型
        $toOtc          = (input('post.toOtc')) ? input('post.toOtc') : 0;

        $number=isset($param['number'])?$param['number']:0;

        $userinfo = model('Users')->where('id',$uid)->find();
        if ($userinfo['trade_state']!=1){
            return ['code'=>0, 'code_dec'=>config($lang.'.task')[21]];
        }

        if(intval($number)<1){
            return ['code'=>0, 'code_dec'=>config($lang.'.task')[4]];
        }

        $log = array();

        try{
            $amount = $param['number']*$param['price'];
            if ($task_type==1){       #卖出:
                $roys = db('UsersRoy')->where('uid',$uid)->find();
                if(!$roys||intval($roys['number'])<=0||intval($roys['number'])<$number){
                    return ['code'=>0, 'code_dec'=>config($lang.'.task')[5]];
                }
            }

            $Task_data = array(
                'task_id'			=>	$param['task_id'],
                'uid'				=>	$uid,
                'username'			=>	$username,
                'status'			=>	1,
                'fuid'				=>	0,
                'is_b'				=>	$toOtc,
                'add_time'			=>	time(),
                'effective_time'	=>	0,
                'number'            =>  $number,
                'user_task_type'    =>  $task_type,
                'price'             =>  $param['price'],
                'total_price'       =>  $param['price']*$number,
                'order_sn' =>'N'.date('YmdHis').rand(0,9).rand(0,9).rand(0,9).rand(0,9)
            );

            $new_id	= model('UserTask')->insertGetId($Task_data);
            model("api/UserLog")->clientlog($uid,"版税买卖:".$new_id,$log);
            if(!$new_id){
                return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
            }

            if($task_type==1){
                $log['卖出得到'] = $amount;
                if ($toOtc){
                    $ret = model('common/UserTotal')->addAmount($uid,$amount,4,'卖出版权');
                }

                $exist=db('users_roy')->where(['uid'=>$uid])->find();
                if($exist){
                    db('users_roy')->where(['uid'=>$uid])->update(['number'=>$exist['number']-$number]);
                }
                model('UserTask')->where('id',$new_id)->update(['status'=>3,'complete_time'=>time()]);
                model("api/UserLog")->clientlog($uid,"版税卖出完成",$log);
            }
            return ['code'=>1, 'code_dec'=>config($lang.'.lang2')[3]];
        }catch (Exception $e){
            $log['异常信息'] = $e->getMessage();
            model("api/UserLog")->clientlog($uid,"买卖版税异常",$log);
            return ['code'=>0, 'code_dec'=>'pay order exception'];
        }
    }

    /**
    挂单
     **/
    public function hangoutTask(){
        $lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
        $param			= input('post.');
        $token			= request()->param('token','','trim') ;
        $userArr = explode(',',auth_code($token,'DECODE'));
        $uid = $userArr[0];

        $number			= request()->param('number',0,'intval') ;
        $person_time			= request()->param('person_time',0,'intval') ;
        $reward_price			= request()->param('reward_price',0,'floatval') ;

        //判断nft有效性
        $task_type = $param['task_type'];

        $userinfo = model('Users')->where('id',$uid)->find();
        if ($userinfo['trade_state']!=1){
            return ['code'=>0, 'code_dec'=>config($lang.'.task')[21]];
        }

        if(!in_array($task_type,[1,2])){
            return (['code'=>0,'code_dec'=>config($lang.'.task')[6]]);
        }

        if($reward_price<=0){
            return (['code'=>0,'code_dec'=>config($lang.'.task')[7]]);
        }

        if($number<=0){
            return (['code'=>0,'code_dec'=>config($lang.'.task')[8]]);
        }

        if($person_time<=0){
            return (['code'=>0,'code_dec'=>config($lang.'.task')[9]]);
        }

        $log = array();

        try {
            $debri_id = $param['debri_id'];
            $deInfo=db('users_goods')->alias('a')->field('a.*,b.credit_type')->join('nft b','a.nft_id=b.id','left')->where(['a.id'=>$debri_id])->find();
            if(empty($deInfo)){
                model("api/UserLog")->clientlog($uid,"挂单拦截-碎片找不到",$log);
                return (['code'=>0,'code_dec'=>config($lang.'.lang2')[1]]);
            }

            //卖出，自己必须有,
            if ($task_type==1){
                if($deInfo['uid'] != $uid){
                    return (['code'=>0,'code_dec'=>config($lang.'.task')[10]]);
                }
                if($deInfo['available_number']<$number){
                    $log['持有数量'] = $deInfo['available_number'];
                    $log['要卖数量'] = $number;
                    model("api/UserLog")->clientlog($uid,"挂单拦截",$log);
                    return (['code'=>0,'code_dec'=>config($lang.'.task')[11]]);
                }
                if($deInfo['status'] !=1 ){
                    return (['code'=>0,'code_dec'=>config($lang.'.task')[12]]);
                }
            }else{
                if ($number>$deInfo['total_number']){
                    $log['总数量'] = $deInfo['total_number'];
                    $log['要卖数量'] = $number;
                    model("api/UserLog")->clientlog($uid,"挂单拦截",$log);
                    return (['code'=>0,'code_dec'=>config($lang.'.task')[13]]);
                }
            }

            $data['uid']= $uid;
            $data['task_type']= $task_type ;
            $data['nft_id']=    $param['nft_id'];
            $data['total_number'] = $number ;
            $data['surplus_number'] = $number ;
            $data['person_time'] = $person_time ;

            $data['credit_type'] = request()->param('credit_type',$deInfo['credit_type'],'intval') ;
            $data['reward_price'] = $reward_price ;
            $data['release_price'] = request()->param('release_price',$deInfo['release_price'],'intval') ;
            $data['recovery_price'] = request()->param('recovery_price',$deInfo['recovery_price'],'intval') ;

            $data['compound_num'] =  $deInfo['compound_num'] ;
            $end_time = 0;
            if (isset($param['cost_hours'])&&intval($param['cost_hours'])>0){
                $end_time = time()+intval($param['cost_hours'])*60*60;
            }
            $data['end_time'] = $end_time;
    //		$data['start_time'] = request()->param('start_time',0,'intval') ;
            $data['uids'] = request()->param('uids','','trim') ;
            $data['status']=$end_time==0?2:1;
            $data['order_number'] ='B'.date('YmdHis').rand(0,9).rand(0,9).rand(0,9).rand(0,9) ;
            $data['trade_number'] ='L'.date('YmdHis').rand(0,9).rand(0,9).rand(0,9).rand(0,9) ;
            $data['add_time'] =time();

            $res = $this->insert($data);

            //把自己可用的碎片数量修改
            db('users_goods')->where(['id'=>$deInfo['id']])->setDec('available_number', $number);

            model("api/UserLog")->clientlog($uid,"挂单成功",$log);
            return ['code'=>1,'data'=>[],'code_dec'=>config($lang.'.lang2')[3]];
        }catch (Exception $e){
            $log['异常信息'] = $e->getMessage();
            model("api/UserLog")->clientlog($uid,"挂单异常",$log);
            return ['code'=>0, 'code_dec'=>'pay order exception'];
        }
    }

    public function payTask()
    {
        $param = input('post.');
        $userArr = explode(',', auth_code($param['token'], 'DECODE'));
        $uid = $userArr[0];
        $username = $userArr[1];
        $lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
        $id = (input('post.id')) ? input('post.id') : 0;    // 任务ID;

        $info = model('api/UserTask')->where(array(['id','=',$id]))->find();//进行中的订单

        if(!$info){
            return ['code'=>0, 'code_dec'=>config($lang.'.task')[14]];
        }
        if($info['status']!=1){
            return ['code'=>0, 'code_dec'=>config($lang.'.task')[15]];
        }

        $userinfo = model('Users')->where('id',$uid)->find();
        if ($userinfo['trade_state']!=1){
            return ['code'=>0, 'code_dec'=>config($lang.'.task')[21]];
        }

        $log = array();

        $task = model('api/Task')->where(array(['id','=',$info['task_id']]))->find();//进行中的订单

        try{
            //otc购买
            if ($param['pay_type']==1){
                //版税购买
                if ($task['status']>0){
                    $existGoods=db('users_goods')->where(['nft_id'=>$task['nft_id'],'uid'=>$task['uid'],'status'=>1])->find();
                    if (empty($existGoods)){
                        $log['碎片不存在'] = $task['nft_id'];
                        model("api/UserLog")->clientlog($uid,"碎片支付异常",$log);
                        return ['code' => 0, 'code_dec' => config($lang.'.lang2')[4]];
                    }
                    if ($existGoods['total_number']<$info['number']){
                        return ['code' => 0, 'code_dec' => config($lang.'.task')[19]];
                    }
                }
                $amount = $info['total_price'];
                $ret = model('common/UserTotal')->addAmount($uid,0-$amount,4,'买入碎片');
                if ($ret==0){
                    return ['code' => 0, 'code_dec' => config($lang.'.task')[20]];
                }

                $ret = $this->buyUserTaskDone($id);
            }else if ($param['pay_type']==2){       //c2c购买,上传资料
                $screenshots = '';
                if (!isset($param['file'])||count($param['file'])==0) {
                    return ['code'=>0, 'code_dec'=>config($lang.'.lang2')[2]];
                }
                $imgcontent = $param['file'][0]['content'];
                $screenFile = base64_image_content($imgcontent, "./upload/image");
                if ($screenFile) {
                    $screenshots = $screenFile;
                }
                $upda = array(
                    'address'=>$param['address'],
                    'credit_type'=>$param['credit_type'],
                    'screenshots'=>$screenshots,
                    'handle_time'=>time(),
                    'status'=>2,
                );
                model('api/UserTask')->where('id',$id)->update($upda);
                model("api/UserLog")->clientlog($uid,"上传支付凭证",$log);
            }
            return ['code'=>1, 'code_dec'=>config($lang.'.lang2')[3]];
        }catch (Exception $e){
            $log['异常信息'] = $e->getMessage();
            model("api/UserLog")->clientlog($uid,"订单支付异常",$log);
            return ['code'=>0, 'code_dec'=>'pay order exception'];
        }
    }

	//领取任务
	public function receiveTask(){
		$param			= input('post.');
		$userArr		= explode(',',auth_code($param['token'],'DECODE'));
		$uid			= $userArr[0];

		$username		= $userArr[1];
		$id				= (input('post.id')) ? input('post.id') : 0;	// 任务ID;
		$lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
		$number=isset($param['number'])?$param['number']:0;

		if(!$id){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}
		$ltime = cache('C_ltime_'.$uid.'_'.$id) ? cache('C_ltime_'.$uid.'_'.$id) : time()-2;
		//10秒
		if(time()-$ltime < 2){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}
		cache('C_ltime_'.$uid.'_'.$id,time()+2);

        $log = array();

        $userinfo = model('Users')->where('id',$uid)->find();
        if ($userinfo['trade_state']!=1){
            return ['code'=>0, 'code_dec'=>config($lang.'.task')[21]];
        }

        try{
            $task = $this->where(array(['id','=',$id]))->find();//进行中的订单

            if(!$task){
                return ['code'=>0, 'code_dec'=>config($lang.'.task')[16]];
            }

            $t = time();
            $start 	= mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
            $end 	= mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));

            if($number<1){
                return ['code'=>0, 'code_dec'=>config($lang.'.task')[4]];
            }

            if ($number>$task['person_time']){
                return ['code'=>0, 'code_dec'=>config($lang.'.task')[17]];
            }

            //自己发的不能自己接
            if($task['uid']==$uid){
                return ['code'=>0, 'code_dec'=>config($lang.'.task')[18]];
            }

            //剩余任务
            if($task['surplus_number']==0){
                return ['code'=>0, 'code_dec'=>config($lang.'.task')[19]];
            }
            if($task['surplus_number']<$number){
                return ['code'=>0, 'code_dec'=>config($lang.'.task')[19]];
            }

            //下一步才支付，这里不校验钱包
//            $cbalance = model('UserTotal')->where('uid',$uid)->value('balance');
//            $tax=db('credit_type')->where(['id'=>$task['credit_type']])->value('tax');
//            //p($cbalance);
//            if($cbalance*$tax<$task['release_price']){
//                return ['code' => 0, 'code_dec' => config($lang.'.task')[20]];
//            }

            //添加领取任务列表
            $Task_data = array(
                'task_id'			=>	$id,
                'uid'				=>	$uid,
                'username'			=>	$username,
                'status'			=>	1,
                'fuid'				=>	$task['uid'],
                'is_b'				=>	1,
                'add_time'			=>	time(),
                'effective_time'	=>	time()+6*3600,
                'number'=>$number,
                'user_task_type'=>$task['task_type']==1?2:1,
                'price'=>$task['reward_price'],
                'total_price'=>$task['reward_price']*$number,
                'order_sn' =>'N'.date('YmdHis').rand(0,9).rand(0,9).rand(0,9).rand(0,9)
            );

            $new_id	= model('UserTask')->insertGetId($Task_data);
            if(!$new_id){
                return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
            }

            //更新次数
            $this->where('id', $id)->Inc('receive_number',$number)->Dec('surplus_number',$number)->update();
            if($task['surplus_number']-$number==0){
                $this->where('id', $id)->update(['status'=>3,'complete_time'=>time()]);
            }

            return ['code'=>1, 'code_dec'=>config($lang.'.lang2')[3]];
        }catch (Exception $e){
            $log['异常信息'] = $e->getMessage();
            model("api/UserLog")->clientlog($uid,"碎片买卖发起异常",$log);
            return ['code'=>0, 'code_dec'=>'pay order exception'];
        }
    }

    //碎片买入订单完成
    public function buyUserTaskDone($userTaskId){
        $info = model('api/UserTask')->where(array(['id','=',$userTaskId]))->find();
        if ($info['status']>2){
            return 0;
        }
        $amount = $info['total_price'];
        $task = model('api/Task')->where(array(['id','=',$info['task_id']]))->find();

        $uid = $info['uid'];
        $user = model('api/Users')->where("id",$uid)->find();

        $log = array();

        //给发布者加钱
        $ret = model('common/UserTotal')->addAmount($task['uid'],$amount,3,'卖出碎片得到');

        $number = $info['number'];

        //roy task,
        if ($task['status']==-1){
            $exist=db('users_roy')->where(['uid'=>$uid])->find();
            if($exist){
                db('users_roy')->where(['uid'=>$uid])->update(['number'=>$exist['number']+$number]);
            }else{
                db('users_roy')->insert([
                    'uid'=>$uid,
                    'username'=>$user['username'],
                    'number'=>$number,
                    'add_time'=>time(),
                ]);
            }
        }else{
            //给买方加碎片
            $existGoods=db('users_goods')->where(['nft_id'=>$task['nft_id'],'uid'=>$uid])->find();
            if($existGoods){
                db('users_goods')->where(['id'=>$existGoods['id']])->update(['total_number'=>$existGoods['total_number']+$number,'available_number'=>$existGoods['available_number']+$number,'status'=>1]);
            }else{
                db('users_goods')->insert([
                    'uid'=>$uid,
                    'nft_id'=>$task['nft_id'],
                    'total_number'=>$number,
                    'available_number'=>$number,
                    'status'=>1,
                    'compound_num'=>$task['compound_num'],
                    'reward_price'=>$task['reward_price'],
                    'recovery_price'=>$task['recovery_price'],
                    'release_price'=>$task['release_price'],
                    'create_time'=>time(),
                ]);
            }

            //给卖方减去碎片数量
            $existGoods=db('users_goods')->where(['nft_id'=>$task['nft_id'],'uid'=>$task['uid'],'status'=>1])->find();
            if($existGoods){
                db('users_goods')->where(['id'=>$existGoods['id']])->setDec('total_number', $number);
                if($number>=$existGoods['total_number']){
                    db('users_goods')->where(['id'=>$existGoods['id']])->update(['status'=>2]);
                }
            }
        }
        model('api/UserTask')->where('id',$userTaskId)->update(['status'=>3,'complete_time'=>time()]);
        model("api/UserLog")->clientlog($uid,"碎片订单买入完成",$log);
        return 1;
    }
	//领取的任务列表
	public function taskOrderlist(){

		$param			= input('post.');
		$userArr		= explode(',',auth_code($param['token'],'DECODE'));
		$uid			= $userArr[0];
		$username		= $userArr[1];

		$task_id		= (input('post.task_id')) ? input('post.task_id') : 0;	// 任务ID下的任务领取列表 如没有就全部的任务列表;

		$lang			= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型

		$is_u			= (input('post.is_u')) ? input('post.is_u') : 2;	// 1是自己发布的;2自己领取的

		$status			= (isset($param['status'])) ? $param['status'] : 1;//状态。1：进行中；2：审核中；3：已完成；4：已失败;5:恶意

		$where = array();

		if($task_id){
			$where[]	=	array(['a.task_id','=',$task_id]);
		}

        if ($status>0){
            $where[]		=	array(['a.status','=',$status]);
        }

		switch($is_u){
			case 1://我发布的 会员领取的任务
				$where[]		=	array(['a.fuid','=',$uid]);
			break;
			case 2://我领取的任务
				$where[]		=	array(['a.uid','=',$uid]);
			break;
		}
		//每页记录数
		$pageSize	= (isset($param['pagesize']) and $param['pagesize']) ? $param['pagesize'] : 10;
		//当前页
		$page		= (isset($param['page']) and $param['page']) ? $param['page'] : 1;


		$dataAll	= [];
		$fields='a.*,b.nft_id,b.release_price,b.credit_type,n.name as nname,n.file,a.status,a.add_time as o_add_time,a.examine_demo as o_examine_demo,a.trial_time,a.effective_time,a.handle_time,a.number,a.id as order_id,b.id as task_id';
		$dataAll = model('UserTask')->alias('a')
		->field($fields)
		->join('ly_task b','b.id=a.task_id','left')
		->join('ly_nft n','b.nft_id=n.id','left')
		->where($where)
		->order('a.add_time DESC')
		->paginate($pageSize)
		->toArray();


		foreach ($dataAll['data'] as $key => &$value) {

			$value['order_id']				= 	$value['order_id'];
			//$value['o_examine_demo']		= 	$value['o_examine_demo'];



			// $value['username']				=	'****'.substr(trim($username),-4);

			// $value['o_username']			= '****'.substr(trim($value['o_username']),-4);



			$value['add_time']				= 	($value['o_add_time']) ? date('Y.m.d-H:i:s', $value['o_add_time']) : '';

			$value['trial_time']			= 	($value['trial_time']) ? date('Y.m.d-H:i:s', $value['trial_time']) : '';

			$value['handle_time']			= 	($value['handle_time']) ? date('Y.m.d-H:i:s', $value['handle_time']) : '';

			$value['effective_time']		= 	($value['effective_time']) ? date('Y.m.d-H:i:s', $value['effective_time']) : '';


			$value['file']=$value['file']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$value['file']):'';

//			$value['status_dec']		=	config('custom.'.$lang.'taskOrderStatus')[$value['status']];
			$value['credit_type_str']= getCreditTypeName($value['credit_type']);

		}

		return ['code'=>1, 'code_dec'=>'success','data'=>$dataAll];
	}

	//领取的任务信息
	public function taskOrderInfo(){

		$param		= input('post.');
		$userArr	= explode(',',auth_code($param['token'],'DECODE'));
		$uid		= $userArr[0];
		$order_id	= (input('post.order_id')) ? input('post.order_id') : 0;	// 任务ID;

		$lang		= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
		if(!$order_id){
			$data['code'] = 0;
			return $data;
		}
		$data = db('UserTask')->alias('a')->field('a.*,b.task_type,b.end_time,n.name as nname,n.file,n.credit_type')
		->join('ly_task b','a.task_id=b.id','left')
		->join('ly_nft n','b.nft_id=n.id','left')

		->where(['a.id'=>$order_id])->find();
		$data['add_time']				= 	($data['add_time']) ? date('Y.m.d-H:i:s', $data['add_time']) : '';

		$data['trial_time']			= 	($data['trial_time']) ? date('Y.m.d-H:i:s', $data['trial_time']) : '';

		$data['handle_time']			= 	($data['handle_time']) ? date('Y.m.d-H:i:s', $data['handle_time']) : '';

		$data['effective_time']		= 	($data['effective_time']) ? date('Y.m.d-H:i:s', $data['effective_time']) : '';


		$data['file']=$data['file']?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$data['file']):'';

//		$data['status_dec']		=	config('custom.'.$lang.'taskOrderStatus')[$data['status']];
//		$data['credit_type_str']= getCreditTypeName($data['credit_type']);
        $examine_demo=$data['examine_demo']?explode(',',$data['examine_demo']):[];
		foreach($examine_demo as &$val){
			$val=$val?($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$val):'';
		}
		$data['examine_demo']=$examine_demo;

		return ['code'=>1, 'code_dec'=>'success','data'=>$data];
	}

	//提交
	public function taskOrderSubmit(){

		$param		= input('post.');
		$userArr	= explode(',',auth_code($param['token'],'DECODE'));
		$uid		= $userArr[0];
		$order_id	= (input('post.order_id')) ? input('post.order_id') : 0;	// 任务ID;
		$lang		= (input('post.lang')) ? input('post.lang') : 'en';	// 语言类型
		$status		= (input('post.status')) ? input('post.status') : 2;	// 状态

		if(!$order_id){

			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		$info = db('UserTask')
			->field('ly_task.status,ly_user_task.status as o_status,ly_user_task.task_id')
			->join('ly_task','ly_task.id=ly_user_task.task_id')
			->where(['ly_task.status'=>1,'ly_user_task.id'=>$order_id,'ly_user_task.uid'=>$uid])
			->find();

		if(!$info){

			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}
		$trial_state_arr =  array(1,2);

		if(!in_array($info['o_status'],$trial_state_arr)){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		switch($status){
			case 6:
				$up_trial_data	=	array(
					'status'	=>	6,
					'trial_time'		=>	time(),//提交时间
				);

				$is_up = model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.uid','=',$uid]))->update($up_trial_data);
				if(!$is_up){
					return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
				}

				//更新次数
				$this->where('id', $info['task_id'])->setDec('receive_number',1);
				$this->where('id', $info['task_id'])->setInc('surplus_number',1);

				return ['code'=>2, 'code_dec'=>config($lang.'.lang')[42]];
			break;
		}
		$examine_demo		=	(input('post.examine_demo')) ? input('post.examine_demo') : '';	// 提交样例
		$examine_demo = str_replace($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'],'',$examine_demo) ;

		if(!$examine_demo){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}


		// if(!is_array($examine_demo)){
		// 	return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		// }

		//foreach($examine_demo as $key2 => $value2){
/*			if(!file_exists('/www/wwwroot/doufenxiang/public'.$value2)){//判断服务器是有该文件
				return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
			}
*/		//}

		//多图
		//$examine_demo		=	json_encode($examine_demo);


		$trial_remarks		=	(input('post.trial_remarks')) ? input('post.trial_remarks') : '';	// 提交说明

		$up_trial_data = array(
			'status'			=>	2,//审核中
			'trial_time'		=>	time(),//提交时间
			'examine_demo'		=>	$examine_demo,//提交样例
			'trial_remarks'		=>	$trial_remarks,//提交说明
		);

		$is_up = model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.uid','=',$uid]))->update($up_trial_data);

		if(!$is_up){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		return ['code'=>1, 'code_dec'=>config($lang.'.lang')[42]];
	}

	//审核
	public function taskOrderTrial(){

		$param		= input('post.');
		$userArr	= explode(',',auth_code($param['token'],'DECODE'));
		$uid		= $userArr[0];

		$order_id	= (input('post.order_id')) ? input('post.order_id') : 1;	// 任务ID;

		$lang		= (input('post.lang')) ? input('post.lang') : 'cn';	// 语言类型

		$status		= (input('post.status')) ? input('post.status') : 2;	// 状态

		if(!$order_id){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		$info = model('UserTask')
		->field('ly_task.reward_price,ly_task.lang,ly_task.total_number,ly_task.order_number,ly_user_task.status as o_status,ly_user_task.uid,ly_user_task.handle_remarks,ly_user_task.task_id,ly_user_task.fuid,ly_user_task.number,ly_task.nft_id,ly_task.compound_num,ly_task.release_price')
		->join('ly_task','ly_task.id=ly_user_task.task_id')
		->where(array(['ly_task.status','=',1],['ly_user_task.id','=',$order_id],['ly_user_task.fuid','=',$uid],['ly_user_task.status','=',2]))->find();
		if(!$info){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		$userinfo		= model('Users')->field('ly_users.vip_level,ly_users.id,ly_users.username,ly_users.sid,user_total.balance')->join('user_total','ly_users.id=user_total.uid')->where('ly_users.id', $info['uid'])->find();

		if(!$userinfo){
			return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
		}

		$handle_remarks		=	(input('post.handle_remarks')) ? input('post.handle_remarks') : '';	// 审核说明

		switch($status){
			case 2://重新提交

				$up_trial_data = array(
					'status'			=>	2,//审核中
					'handle_remarks'	=>	$handle_remarks,//审核说明
					'handle_time'		=>	time(),
				);

				$is_up = model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.fuid','=',$uid],['ly_user_task.status','=',2]))->update($up_trial_data);

				if(!$is_up){
					return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
				}
				return ['code'=>1, 'code_dec'=>config($lang.'.lang')[42]];

			break;
			case 3://完成
				$up_trial_data = array(
					'status'			=>	3,//完成
					'handle_remarks'	=>	$handle_remarks,//审核说明
					'handle_time'		=>	time(),//审核时间
					'complete_time'		=>	time(),//完成时间
				);
				$is_up = model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.fuid','=',$uid],['ly_user_task.status','=',2]))->update($up_trial_data);
				if(!$is_up){
					return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
				}

				//给用户加碎片
				$existGoods=db('users_goods')->where(['nft_id'=>$info['nft_id'],'uid'=>$info['uid'],'status'=>1])->find();
				if($existGoods){
					db('users_goods')->where(['id'=>$existGoods['id']])->update(['total_number'=>$existGoods['total_number']+$info['number'],'available_number'=>$existGoods['available_number']+$info['number']]);
				}else{
					db('users_goods')->insert([
						'uid'=>$info['uid'],
						'nft_id'=>$info['nft_id'],
						'total_number'=>$info['number'],
						'available_number'=>$info['number'],
						'status'=>1,
						'price'=>$info['release_price'],
						'compound_num'=>$info['compound_num'],
						'create_time'=>time(),
					]);
				}
				$y_surplus_number	=	db('Task')->where(['id'=>$info['task_id'],'status'=>1])->value('surplus_number');
				$count=db('UserTask')->where("task_id = {$info['task_id']} and (status=1 or status=2)")->count();
				if($count==0 && $y_surplus_number==0){
					$arr = array(
						'status'			=>4,//完成
						'complete_time'		=>	time(),//完成时间
					);
					$this->where(array(['id','=',$info['task_id']],['uid','=',$info['fuid']],['status','=',2]))->update($arr);
				}


				//任务提成
				// $commission		=	$info['reward_price'];//任务单价

				// if($commission > 0){

				// 	$userinfo		= model('Users')->field('ly_users.id,ly_users.username,ly_users.sid,user_total.balance')->join('user_total','ly_users.id=user_total.uid')->where('ly_users.id', $info['uid'])->find();

				// 	if(!$userinfo){
				// 		$up_trial_data_r	=	array(
				// 			'status'			=>	2,//审核
				// 			'handle_remarks'	=>	$info['handle_remarks'],//审核说明
				// 			'handle_time'		=>	time(),
				// 		);
				// 		model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.fuid','=',$uid],['ly_user_task.status','=',3]))->update($up_trial_data_r);
				// 		return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
				// 	}
					// //加余额钱
					// $is_up_to = model('UserTotal')->where('uid', $userinfo['id'])->setInc('balance', $commission);

					// if(!$is_up_to){
					// 	$up_trial_data_r	=	array(
					// 		'status'			=>	2,//审核
					// 		'handle_remarks'	=>	$info['handle_remarks'],//审核说明
					// 		'handle_time'		=>	time(),
					// 	);
					// 	 model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.fuid','=',$uid],['ly_user_task.status','=',3]))->update($up_trial_data_r);
					// 	return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
					// }


					// //加总金额
					// model('UserTotal')->where('uid', $userinfo['id'])->setInc('total_balance', $commission);
					// // 流水
					// $financial_data_p['uid'] 					= $userinfo['id'];
					// $financial_data_p['username'] 				= $userinfo['username'];
					// $financial_data_p['order_number'] 			= $info['order_number'];
					// $financial_data_p['trade_number'] 			= 'L'.trading_number();
					// $financial_data_p['trade_type'] 			= 6;
					// $financial_data_p['trade_before_balance']	= $userinfo['balance'];
					// $financial_data_p['trade_amount'] 			= $commission;
					// $financial_data_p['account_balance'] 		= $userinfo['balance'] + $commission;
					// $financial_data_p['remarks'] 				= config($info['lang'].'.lang')[160];
					// $financial_data_p['types'] 					= 1;	// 用户1，商户2

					// model('common/TradeDetails')->tradeDetails($financial_data_p);

					// //已经完成的 和 总的任务数 一样 更新任务 完成

					// $y_surplus_number	=	model('UserTask')->where(array(['task_id','=',$info['task_id']],['status','=',3]))->count();

					// if($y_surplus_number==$info['total_number']){
					// 	$arr = array(
					// 		'status'			=>4,//完成
					// 		'complete_time'		=>	time(),//完成时间
					// 	);
					// 	$this->where(array(['id','=',$info['task_id']],['uid','=',$info['fuid']],['status','=',3]))->update($arr);
					// }

					// //上级返点
					// if($userinfo['sid']){
					// 	$rebatearr = array(
					// 		'num'			=>	1,
					// 		'uid'			=>	$userinfo['id'],
					// 		'sid'			=>	$userinfo['sid'],
					// 		'order_number'	=>	$info['order_number'],
					// 		'commission'	=>	$commission,
					// 		'lang'			=>	$info['lang'],
					// 	);

					// 	$this->setrebate($rebatearr);
					// }
				//}

				//更新每日完成任务次数
				// $UserDailydata = array(
				// 	'uid'				=>	$userinfo['id'],
				// 	'username'			=>	$userinfo['username'],
				// 	'field'				=>	'w_t_o_n',//完成
				// 	'value' 			=>	1,
				// );
				// model('UserDaily')->updateReportfield($UserDailydata);

				return ['code'=>1, 'code_dec'=>config($lang.'.lang')[42]];

			break;
			case 4://已失败

				$up_trial_data = array(
					'status'			=>	4,//已失败
					'handle_remarks'	=>	$handle_remarks,//审核说明
					'handle_time'		=>	time(),
				);
				$is_up = model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.fuid','=',$uid],['ly_user_task.status','=',2]))->update($up_trial_data);

				if(!$is_up){
					return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
				}

				//失败加任务
				//更新次数
				$this->where('id', $info['task_id'])->Dec('receive_number',$info['number'])->Inc('surplus_number',$info['number'])->update();

				//更新每日失败任务次数
				// $UserDailydata = array(
				// 	'uid'				=>	$userinfo['id'],
				// 	'username'			=>	$userinfo['username'],
				// 	'field'				=>	's_t_o_n',//失败
				// 	'value' 			=>	1,
				// );
				// model('UserDaily')->updateReportfield($UserDailydata);

				return ['code'=>1, 'code_dec'=>config($lang.'.lang')[42]];
			break;
			case 5://恶意
				$up_trial_data = array(
					'status'			=>	5,//恶意
					'handle_remarks'	=>	$handle_remarks,//审核说明
					'handle_time'		=>	time(),
				);

				$is_up = model('UserTask')->where(array(['ly_user_task.id','=',$order_id],['ly_user_task.fuid','=',$uid],['ly_user_task.status','=',2]))->update($up_trial_data);

				if(!$is_up){
					return ['code'=>0, 'code_dec'=>config($lang.'.lang')[41]];
				}

				//失败加任务
				//更新次数
				$this->where('id', $info['task_id'])->Dec('receive_number',1)->Inc('surplus_number',1)->update();

				//更新每日恶意任务次数
				$UserDailydata = array(
					'uid'				=>	$userinfo['id'],
					'username'			=>	$userinfo['username'],
					'field'				=>	'e_t_o_n',//恶意
					'value' 			=>	1,
				);

				model('UserDaily')->updateReportfield($UserDailydata);

				return ['code'=>1, 'code_dec'=>config($lang.'.lang')[42]];

			break;
		}
	}

	public function setrebate($param){
		if($param['num']<4){//上三级

			$rebate			=	model('Setting')->where('id',1)->value('rebate'.$param['num']);//返点值
			if($rebate){

				$rebate_amount	=	round($param['commission']*($rebate/100),2);

				if($rebate_amount>0){
					$userinfo = model('Users')->field('ly_users.id,ly_users.username,ly_users.sid,user_total.balance')->join('user_total','ly_users.id=user_total.uid')->where('ly_users.id', $param['sid'])->find();

					if($userinfo){

						$is_up_to = model('UserTotal')->where('uid', $userinfo['id'])->setInc('balance', $rebate_amount);

						if($is_up_to){
							model('UserTotal')->where('uid', $userinfo['id'])->setInc('total_balance', $rebate_amount);
							// 流水
							$financial_data_p['uid'] 					= $userinfo['id'];
							$financial_data_p['sid']					= $param['uid'];
							$financial_data_p['username'] 				= $userinfo['username'];
							$financial_data_p['order_number'] 			= $param['order_number'];
							$financial_data_p['trade_number'] 			= 'L'.trading_number();
							$financial_data_p['trade_type'] 			= 5;
							$financial_data_p['trade_before_balance']	= $userinfo['balance'];
							$financial_data_p['trade_amount'] 			= $rebate_amount;
							$financial_data_p['account_balance'] 		= $userinfo['balance'] + $rebate_amount;
							$financial_data_p['remarks'] 				= config($param['lang'].'.lang')[161];
							$financial_data_p['types'] 					= 1;	// 用户1，商户2

							model('common/TradeDetails')->tradeDetails($financial_data_p);
						}
					}
					if($userinfo['sid']){
						$rebatearr = array(
							'num'			=>	$param['num']+1,
							'uid'			=>	$userinfo['id'],
							'sid'			=>	$userinfo['sid'],
							'order_number'	=>	$param['order_number'],
							'commission'	=>	$param['commission'],
							'lang'			=>	$param['lang'],
						);
						$this->setrebate($rebatearr);
					}
				}
			}
		}
	}
	public function taskzy(){
		$param      = input('get.');
		$pageSize   = 10000;
		$pageNo     = $param['page_no'];
		$limitOffset    = ($pageNo - 1) * $pageSize;
		$users = model('Users')->field('username,realname,vip_level')->order('id asc')->limit($limitOffset, $pageSize)->select()->toArray();
		 foreach ($users as $key => $value) {
			 file_put_contents("username12.txt", $value['username'].PHP_EOL, FILE_APPEND);
		 }
	}
}
